package com.powernode.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.powernode.dto.LoginUser;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

@Component
public class LoginUserHolder {

    /**
     * 获取登录用户对象
     */
    public LoginUser getLoginUser() {
        // 以解耦的方式获取登录用户对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取请求request对象
        javax.servlet.http.HttpServletRequest request = requestAttributes.getRequest();
        // 获取用户
        String userStr = request.getHeader("user");
        System.out.println("userStr = " + userStr);
        JSONObject jsonObject = new JSONObject(userStr);
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(jsonObject.getStr("username"));
        loginUser.setId(jsonObject.getLong("id"));
        loginUser.setMobile(jsonObject.getStr("mobile"));
        loginUser.setRoles(Convert.toList(String.class,jsonObject.getStr("authorities")));
        return loginUser;
    }

    /**
     * 获取登录用户id
     */
    public Long getLoginUserId() {
        return Optional.of(this.getLoginUser()).map(LoginUser::getId).orElse(null);
    }
}
